package com.cat.test.test01;

import java.util.*;
import java.util.function.*;

/**
 * @author 曲大人的喵
 * @description
 * @create 2025/10/26 10:31
 * @since JDK17
 */

public class SimpleStream<T> {
    private SimpleStream(Collection<T> collection) {
        this.collection = collection;
    }
    Collection<T> collection;
    static <T> SimpleStream<T> of(Collection<T> collection) {
        return new SimpleStream<>(collection);
    }
    public SimpleStream<T>filter(Predicate<T> predicate) {
        Collection<T> result = new ArrayList<>();
        for (T t : collection) {
            if (predicate.test(t)) {
                result.add(t);
            }
        }

        return new SimpleStream<>(result);
    }
    public <U>SimpleStream<U>map(Function<T, U> function) {
        Collection<U> result = new ArrayList<>();
        for (T t : collection) {
            result.add(function.apply(t));
        }

        return new SimpleStream<>(result);
    }

    public void forEach(Consumer<T> consumer) {
        for (T t : collection) {
            consumer.accept(t);
        }
    }
    public T reduce(T o, BinaryOperator<T> operator) {
        for (T t : collection) {
            o = operator.apply(o, t);
        }
        return o;
    }
    public <C> C collect(Supplier<C> supplier, BiConsumer<C, T> consumer) {
        C c = supplier.get();
        for (T t : collection) {
            consumer.accept(c, t);
        }

        return c;
    }


    public static void main(String[] args) {
        List<Integer> list = List.of(1, 2, 3, 4, 5);
        SimpleStream.of(list).filter(x -> (x & 1) == 1).map(x -> x * x).forEach(System.out::println);
        System.out.println(SimpleStream.of(list).reduce(0, Integer::sum));
        System.out.println(SimpleStream.of(list).reduce(Integer.MAX_VALUE, Integer::min));
        System.out.println(SimpleStream.of(list).reduce(Integer.MIN_VALUE, Integer::max));
        System.out.println("=============================分割线==============================");
        SimpleStream.of(list).collect(HashSet::new, HashSet::add).forEach(System.out::println);
        StringBuilder stringBuilder = SimpleStream.of(list).collect(StringBuilder::new, StringBuilder::append);
        System.out.println(stringBuilder);
        StringJoiner joiner = SimpleStream.of(list).map(String::valueOf).collect(() -> new StringJoiner("-"), StringJoiner::add);
        System.out.println(joiner);
        System.out.println("=============================分割线==============================");
        Map<Integer, Integer> map = SimpleStream.of(List.of(1, 1, 2, 3, 3, 4, 4, 2)).
                collect(HashMap::new, (Map<Integer, Integer> m, Integer t) -> m.merge(t, 1, Integer::sum));
        System.out.println(map);
    }
}
